﻿using System;
using System.Collections.Generic;
using System.Text;
using OSS.NBEncode.Entities;

namespace OSS.NBEncode.Extensions
{
	public static class BDictionsExtensions
	{
		public static IBObject FindSection(this BDictionary dictionary, string sectionName)
		{
			if (dictionary == null)
				throw new ArgumentNullException();

			IBObject result = null;
			foreach (KeyValuePair<BByteString, IBObject> keyValuePair in dictionary.Value)
			{
				if (keyValuePair.Value is BDictionary)
					result = FindSection((BDictionary) keyValuePair.Value, sectionName);

				
				if (keyValuePair.Value is BList)
					result = ((BList)keyValuePair.Value).FindSection(sectionName);
				
				if (result != null)
					break;

				string key = keyValuePair.Key.ConvertToText(Encoding.ASCII);
				if (key == sectionName)
					return keyValuePair.Value;
			}

			return result;
		}
	}
}
